//
//  HomeTableViewController.swift
//  0623微博(swift)
//
//  Created by 岳挺 on 15/6/24.
//  Copyright © 2015年 yueting. All rights reserved.
//

import UIKit
import SVProgressHUD

let YTWeiboNormalCell = "WeiboNormalCell"
let ytweiboForwardCell = "weiboForwardCell"

class HomeTableViewController: BaseTableViewController {
    
    var upPullRefresh = false
    var weiboStatus : [Status]? {
        didSet{
            
            tableView.reloadData()
            
            refreshControl?.endRefreshing()
        }
    }
    
    //自定义缓存行高
    lazy var heighCache = [Int : CGFloat]()

    override func viewDidLoad() {
        super.viewDidLoad()
        visibleLoginView?.setUpSubviewInfo("visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
        setHomeBarButton()
//        loadWeiboStatus()
        preparRefreshControl()
        preparTableView()
        
    }
    
    func loadWeiboStatus (){
        
        self.refreshControl?.beginRefreshing()
        
        var since_id = weiboStatus?.first?.id ?? 0
        
        var max_id = 0
        if upPullRefresh {
            since_id = 0
            max_id = weiboStatus?.last?.id ?? 0
        }

        Status.loadData(since_id, max_id: max_id, finished: {(statuses, error) -> () in
            
            
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            
            if statuses == nil{
                return
            }
            
            if since_id > 0 {
                self.weiboStatus = statuses! + self.weiboStatus!
            }else if max_id > 0{
                self.weiboStatus = self.weiboStatus! + statuses!
                self.upPullRefresh = false
            }else{
                self.weiboStatus = statuses
            }
        })
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        visibleLoginView?.iconImageRotate()
    }
    
    // MARK: - 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        print(weiboStatus!.count)
//        return weiboStatus!.count
        return weiboStatus?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status = weiboStatus![indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseCellString(status), forIndexPath: indexPath) as! WeiboStatusCell
//        print(status.retweeted_status)
        
        if indexPath.row == (weiboStatus?.count)! - 1{
            upPullRefresh = true
            loadWeiboStatus()
        }
        cell.status = status
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let s = weiboStatus![indexPath.row]
        
        if (heighCache[s.id] != nil) {
            return heighCache[s.id]!
        }
        
        let cellStr = reuseCellString(s)
        var cls : AnyClass = WeiboNormalCell.self
        if cellStr == ytweiboForwardCell {
            cls = weiboForwardCell.self
        }
        
        let cell = cls.new() as! WeiboStatusCell
        let heigh = cell.rowHights(s)
        heighCache[s.id] = heigh
        return cell.rowHights(s)
    }
    
    //根据是原创微博还是返回微博，决定cell的重用id
    func reuseCellString (status : Status) -> String{
        return status.retweeted_status == nil ? YTWeiboNormalCell : ytweiboForwardCell
    }
    
    //准备tableView
    func preparTableView (){
        tableView.registerClass(weiboForwardCell.self, forCellReuseIdentifier: ytweiboForwardCell)
        tableView.registerClass(WeiboNormalCell.self, forCellReuseIdentifier: YTWeiboNormalCell)
        tableView.allowsSelection = false
//        tableView.estimatedRowHeight = 200
//        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    
    //准备刷新控件
    func preparRefreshControl (){
        refreshControl = WeiboRefreshControl()
        refreshControl?.addTarget(self, action: "loadWeiboStatus", forControlEvents: UIControlEvents.ValueChanged)
        
        loadWeiboStatus()
    }
    
    // MARK: - 中间文字按钮和监听方法
    func setTitleBtn (){
        let title = sharedUserAccount?.name
        let btn = HomeTitleButton.titleBtnWithTitle(title!)
        btn.addTarget(self, action: "titleBtnDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = btn
    }
    
    func titleBtnDidClick (sender : HomeTitleButton){
        sender.selected = !sender.selected
    }
    
    // MARK: - 设置导航条左右按钮
    func setHomeBarButton (){
        if sharedUserAccount != nil {
            
            navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch" , highlightImageName: nil)
            let leftBtn = navigationItem.leftBarButtonItem?.customView as! UIButton
            leftBtn.addTarget(self, action: "leftBtnDidClick", forControlEvents: UIControlEvents.TouchUpInside)
            navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop" , highlightImageName: nil)
            let rightBtn = navigationItem.rightBarButtonItem?.customView as! UIButton
            rightBtn.addTarget(self, action: "rightBtnDidClick", forControlEvents: UIControlEvents.TouchUpInside)
            setTitleBtn()
        }
    }
    
    // MARK: - 左右按钮的监听方法
    func leftBtnDidClick (){
        print("leftBtnDidClick")
    }
    
    func rightBtnDidClick (){
        print("rightBtnDidClick")
        let sb = UIStoryboard(name: "ORCode", bundle: NSBundle.mainBundle())
        let vc = sb.instantiateInitialViewController()
        presentViewController(vc!, animated: true, completion: nil)
    }
}
